import sys
import threading

from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtWidgets import QMainWindow, QPushButton, QWidget, QHBoxLayout, QVBoxLayout, QStackedWidget, \
    QApplication, QDesktopWidget, QFrame, QLabel, QPlainTextEdit, QMessageBox
from src.python.gui.page.main_page import MainPage
from src.python.gui.page.fuhau_page import FuhuaPage
from src.python.tools.logHandler import logger

log = logger()


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initValidateUI()

    def initValidateUI(self):
        # 设置主窗口标题
        self.setWindowTitle("风云-自动孵化器")

        # 设置窗口大小
        self.setFixedSize(400, 280)

        # 设置图标
        icon = QIcon("resource/icon.ico")
        self.setWindowIcon(icon)
        self.setIconSize(QSize(50, 50))

        # 获取屏幕的大小
        screen = QDesktopWidget().screenGeometry()

        # 计算窗口的位置，使其位于右上方
        window_x = screen.width() - self.width()
        window_y = 0

        self.move(window_x, window_y)  # 设置窗口位置

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        layout = QVBoxLayout()
        self.central_widget.setLayout(layout)

        self.desc_label = QLabel("\n请联系管理员获取验证码!!\n\n")
        self.desc_label.setAlignment(Qt.AlignCenter)  # 设置标签文本居中对齐

        self.input_field = QPlainTextEdit()
        try:
            with open("validate.conf", "r") as f:
                content = f.read()
        except Exception as e:
            content = ""
        if content == "":
            self.input_field.setPlaceholderText("请输入...")
        else:
            self.input_field.setPlainText(content)
        self.input_field.setFixedHeight(100)

        self.submit_button = QPushButton("提交")
        self.submit_button.setFixedSize(350, 50)

        # 创建一个水平布局来放置按钮并居中对齐
        self.button_layout = QHBoxLayout()
        self.button_layout.addWidget(self.submit_button)
        self.button_layout.setAlignment(Qt.AlignCenter)

        # 设置字体为加粗、大号
        font = QFont()
        font.setBold(True)
        font.setPointSize(16)  # 设置字体大小log.info(f"验证信息:{resp}")
        self.desc_label.setFont(font)

        layout.addWidget(self.desc_label)
        layout.addWidget(self.input_field)
        layout.addLayout(self.button_layout)

        # 设置按钮和标签的样式
        self.submit_button.setStyleSheet("QPushButton { background-color: #4CAF50; color: white; }"
                                         "QPushButton:hover { background-color: #45a049; }"
                                         "QLabel { font-size: 18px; }")

        # 连接按钮点击事件到验证槽函数
        self.submit_button.clicked.connect(self.validate_input)

    def validate_input(self):
        validate = self.input_field.toPlainText()
        # 后门验证
        if validate == "asd321":
            self.initMainUI()
            return
        else:
            self.showValidateErrorBox(validate)

        # # 联网验证
        # computer_cede = computerCode().getMachineCode()
        # resp = verification(computer_cede, validate)
        # if resp in ["OK", "ok"]:
        #     log.info(f"验证通过!")
        #     with open("validate.conf", "w") as f:
        #         f.write(validate)
        #     self.initMainUI()
        # else:
        #     self.showNoSelectResolutionBox(resp)

    def showValidateErrorBox(self, message):
        log.warning(f"验证信息:{message}")
        QMessageBox.information(self, f'{message}', '验证失败，请联系管理员！', QMessageBox.Ok)

    def initMainUI(self):
        # 创建主窗口部件
        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)

        # 创建一个带边框的 QFrame
        frame = QFrame(self)
        frame.setFrameShape(QFrame.NoFrame)  # 设置无边框

        # 设置 QFrame 的底边框样式表
        frame.setStyleSheet("QFrame {border-bottom: 2px solid red;}")

        # 创建按钮布局
        button_layout = QHBoxLayout()

        # 创建导航按钮
        self.index_button = QPushButton("主页", self)
        self.fuhua_button = QPushButton("孵化", self)
        self.no_button = QPushButton("待定..", self)
        self.index_button.clicked.connect(self.showMainPage)
        self.fuhua_button.clicked.connect(self.showFuhuaPage)
        self.no_button.setEnabled(False)

        # 将按钮添加到水平布局中
        button_layout.addWidget(self.index_button)
        button_layout.addWidget(self.fuhua_button)
        button_layout.addWidget(self.no_button)

        # 将按钮布局添加到 QFrame 中
        frame.setLayout(button_layout)  # 将按钮布局设置为 QFrame 的布局

        # 创建堆叠窗口部件
        self.stackedWidget = QStackedWidget()

        # 创建页面1并添加到堆叠窗口
        self.main_page = MainPage()
        self.stackedWidget.addWidget(self.main_page)

        # 创建页面2并添加到堆叠窗口
        self.fuhua_page = FuhuaPage()
        self.stackedWidget.addWidget(self.fuhua_page)

        # 创建主布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(frame)  # 将 QFrame 添加到主布局中
        main_layout.addWidget(self.stackedWidget)

        # 设置主窗口的布局
        self.central_widget.setLayout(main_layout)

        logger().info("初始化页面完成")

    def showMainPage(self):
        # 显示页面1
        self.stackedWidget.setCurrentIndex(0)
        logger().info("切换至首页")

    def showFuhuaPage(self):
        # 显示页面2
        self.stackedWidget.setCurrentIndex(1)
        logger().info("切换至孵化页")


def startGui():
    # 创建Qt应用程序实例
    app = QApplication(sys.argv)

    # 创建主窗口并显示
    window = MainWindow()
    window.show()

    # 运行应用程序事件循环
    sys.exit(app.exec_())


def threadStartGui():
    gui_thread = threading.Thread(target=startGui, name="gui线程")
    gui_thread.start()
    logger().info(f"创建窗口程序线程: {gui_thread}")
